package com.wosiliujing.learning.aspect;

import com.wosiliujing.learning.util.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

/**
 * @author 刘靖
 * @date 2019-10-08 11:01
 */
@Component
@Aspect
@Slf4j
public class AuthTokenAspect {

    /**
     * 处理返回的token格式
     * @param point 切面参数
     * @return 格式化后的token
     * @throws Throwable 抛出异常
     */
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handle(ProceedingJoinPoint point) throws Throwable{
        Object proceed = point.proceed();
        if(proceed != null){
            ResponseEntity<OAuth2AccessToken> responseEntity =  (ResponseEntity<OAuth2AccessToken>)proceed;
            if(responseEntity.getStatusCode().is2xxSuccessful()){
                return new ResponseEntity<RestResult>(RestResult.data(responseEntity.getBody()),responseEntity.getHeaders(),responseEntity.getStatusCode());
            }
        }
        return null;
    }

}
